import { useCallback, useEffect, useImperativeHandle, useState } from 'react';
import { Form, Tabs, DatePicker } from 'antd';
import moment from 'moment';
import { deepClone } from '@inbiz/utils';
import { getMessage } from '@inbiz/react';
import NumberGroup from './NumberGroup';
import MultiSelect from './MultiSelect';
import { getColumnList } from './MultiSelect/service';
import './index.less';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

const FilterModal = (props: { list: any[]; active: number; refs: any }) => {
  const { list, active } = props;
  const [newList, setNewList] = useState([]);
  const [form] = Form.useForm();

  // 向上暴露提交方法
  useImperativeHandle(props.refs, () => ({
    submit: submit,
  }));

  // 初始化回填数据
  useEffect(() => {
    let list: any[] = deepClone(props.list);
    let obj: any = {};
    list.forEach((item: any) => {
      let arr: any[] = item.Data || [];
      if (item.FilterType === 'date' && arr.length > 1) {
        arr[0] = moment(arr[0]);
        arr[1] = moment(arr[1]);
      }
      obj[item.Name] = arr;
    });
    const promises = list?.map((item) => {
      return new Promise(async (resolve, reject) => {
        const _filterList = await getColumnList({
          soureOutId: item?.soureOutId,
          columnName: item?.Name,
          keyWork: '',
        });
        resolve({
          ...item,
          filterList: _filterList || [],
        });
      })
    });
    Promise.all(promises).then((res) => {
      setNewList(res)
    })
    form.setFieldsValue(obj);
  }, []);

  // 确认数据提交
  const submit = useCallback(async () => {
    let res = await form.validateFields();
    const arr = deepClone(list);
    arr.forEach((item: any) => {
      let value = res[item.Name] || [];
      if (item.FilterType === 'date') {
        let newDate: string[] = [];
        if (value.length > 1) {
          newDate[0] = moment(value[0]).format('YYYY-MM-DD');
          newDate[1] = moment(value[1]).format('YYYY-MM-DD');
        }
        item.Data = newDate;
      } else {
        item.Data = value;
      }
    });
    return arr;
  }, [form, list]);

  return (
    <>
      <div className={'inbiz-bi-filter-setter-filter-modal-content'}>
        <Form form={form}>
          <Tabs defaultActiveKey={active.toString()}>
            {newList.map((item: any, idx: number) => {
              let option: string[] = [];
              if (item.FilterType === 'string') {
                let arr: string[] = [];
                item.Data?.forEach((val: string) => {
                  if (!item.filterList.includes(val)) {
                    arr.push(val);
                  }
                });
                option = [...item.filterList, ...arr];
              }
              return (
                <TabPane
                  tab={item.Label || item.Name}
                  key={idx}
                  forceRender={true}
                >
                  {item.FilterType === 'date' && (
                    <Form.Item name={item.Name}>
                      <RangePicker
                        allowClear
                        placeholder={[
                          getMessage('BiFilterModal.begin_time'),
                          getMessage('BiFilterModal.end_time'),
                        ]}
                      />
                    </Form.Item>
                  )}
                  {item.FilterType === 'count' && (
                    <Form.Item name={item.Name}>
                      <NumberGroup />
                    </Form.Item>
                  )}
                  {item.FilterType === 'string' && (
                    <Form.Item name={item.Name}>
                      <MultiSelect
                        option={option}
                        outId={item.soureOutId}
                        name={item.Name}
                      />
                    </Form.Item>
                  )}
                </TabPane>
              );
            })}
          </Tabs>
        </Form>
      </div>
    </>
  );
};

export default FilterModal;
